import { View, Text } from "@tarojs/components";
import {
  Form,
  Cell,
  Input,
  Button,
  Uploader,
  Textarea,
  Toast,
} from "@taroify/core";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import Footer from "@/components/Footer/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import { useRef, useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import VideoPng from "@/assets/images/video.png";
import Taro from "@tarojs/taro";
import { requestPOST } from "@/request";

export default function Index() {
  const businessInfo = useSelector((state: RootState) => state.business.info);

  const [info, setInfo] = useState<any>({
    introduction: businessInfo.introduction,
    phone: businessInfo.phone,
    address: businessInfo.address,
    email: businessInfo.email,
    video: businessInfo.video,
    enterpriseQualification: businessInfo.enterpriseQualification,
    wxAccount: businessInfo.wxAccount,
    producer: businessInfo.producer,
    establishment: businessInfo.establishment,
    logoImage: businessInfo.logoImage,
    codeImage: businessInfo.codeImage,
    image: businessInfo.image,
    id: businessInfo.id,
    businessName: businessInfo.businessName,
    images: businessInfo.images,
    longitude: businessInfo.longitude,
    latitude: businessInfo.latitude,
    chinaAddress: businessInfo.chinaAddress,
    whatsapp: businessInfo.whatsapp,
  });

  const priviewImage = (sources, current, type = "image") => {
    sources =
      sources &&
      sources
        .split(",")
        .map((item) => ({ url: process.env.TARO_APP_API + item, type }));
    Taro.previewMedia({
      sources: sources || [],
      current: current,
    });
  };

  const onUpload = (key, limit = 0, type = "img") => {
    if (type === "img") {
      Taro.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
      }).then(({ tempFiles, tempFilePaths }) => {
        const size = tempFiles[0].size;
        if (size > 500 * 1024) {
          return Toast.open({ type: "fail", message: "大小超过500kb无法上传" });
        }
        Taro.showLoading({
          title: "上传中...",
        });

        Taro.uploadFile({
          url: process.env.TARO_APP_API + "/other/upload",
          filePath: tempFilePaths[0],
          name: "file",
          success(res) {
            const { relativeUrl } = JSON.parse(res.data).data;
            setInfo({
              ...info,
              [key]: limit
                ? `${info[key] ? info[key] + "," : ""}${relativeUrl}`
                : relativeUrl,
            });
            Taro.hideLoading();
          },
          fail() {
            Toast.open({ type: "fail", message: "upload error" });
          },
        });
      });
    } else {
      Taro.chooseMedia({
        count: 1,
        mediaType: ["video"],
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
      }).then(({ tempFiles }) => {
        Taro.showLoading({
          title: "上传中...",
        });

        Taro.uploadFile({
          url: process.env.TARO_APP_API + "/other/upload",
          filePath: tempFiles[0].tempFilePath,
          name: "file",
          success(res) {
            Taro.hideLoading();
            const { relativeUrl } = JSON.parse(res.data).data;
            setInfo({
              ...info,
              [key]: limit
                ? `${info[key] ? info[key] + "," : ""}${relativeUrl}`
                : relativeUrl,
            });
          },
          fail() {
            Toast.open({ type: "fail", message: "upload error" });
          },
        });
      });
    }
  };

  const onSubmit = () => {
    requestPOST("shop/shopAddIntroduction", {
      ...info,
    }).then(() => {
      Toast.open({ type: "success", message: "保存成功" });
      formRef.current?.reset();
    });
  };

  const formRef = useRef<any>();

  return (
    <View className="taroBox">
      <HeaderSearch />
      <Header />
      <View>
        <GoodsTitle title="简介配置" isMore={false} />
        <View>
          <Form ref={formRef} defaultValues={info} onSubmit={() => onSubmit()}>
            <Cell.Group inset>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    添加轮播图
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      推荐尺寸1920*670,图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.images &&
                        info.images.split(",").map((item, index) => (
                          <Uploader.Image
                            key={index}
                            url={process.env.TARO_APP_API + item}
                            mode="aspectFill"
                            onClick={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              priviewImage(info.images, index);
                            }}
                            onRemove={(e) => {
                              e.preventDefault();
                              e.stopPropagation();
                              let arr = info.images.split(",");
                              arr.splice(index, 1);
                              setInfo({
                                ...info,
                                images: arr.join(","),
                              });
                            }}
                          ></Uploader.Image>
                        ))}
                      <Uploader.Upload onClick={() => onUpload("images", 1)} />
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    添加企业资质图片
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      推荐尺寸1920*100,图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.enterpriseQualification && (
                        <Uploader.Image
                          key={info.enterpriseQualification}
                          url={
                            process.env.TARO_APP_API +
                            info.enterpriseQualification
                          }
                          mode="aspectFill"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            priviewImage(info.enterpriseQualification, 0);
                          }}
                          onRemove={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setInfo({
                              ...info,
                              enterpriseQualification: "",
                            });
                          }}
                        ></Uploader.Image>
                      )}
                      {!info.enterpriseQualification && (
                        <Uploader.Upload
                          onClick={() => onUpload("enterpriseQualification", 0)}
                        />
                      )}
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    企业视频
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      mp4格式
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.video && (
                        <Uploader.Image
                          key={info.video}
                          url={VideoPng}
                          mode="aspectFill"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            priviewImage(info.video, 0, "video");
                          }}
                          onRemove={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            setInfo({
                              ...info,
                              video: "",
                            });
                          }}
                        ></Uploader.Image>
                      )}
                      {!info.video && (
                        <Uploader.Upload
                          onClick={() => onUpload("detailsVideo", 1, "video")}
                        />
                      )}
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    商家logo图片
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      推荐尺寸800*800,图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.logoImage && (
                        <Uploader.Image
                          key={info.logoImage}
                          url={process.env.TARO_APP_API + info.logoImage}
                          mode="aspectFill"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            priviewImage(info.logoImage, 0);
                          }}
                          onRemove={(e) => {
                            e.preventDefault();
                            e.stopPropagation();

                            setInfo({
                              ...info,
                              logoImage: "",
                            });
                          }}
                        ></Uploader.Image>
                      )}
                      {!info.logoImage && (
                        <Uploader.Upload
                          onClick={() => onUpload("logoImage", 1)}
                        />
                      )}
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item style={{ flexDirection: "column", gap: "10px" }}>
                <Form.Label style={{ width: "100%" }}>
                  <Text>
                    商家二维码
                    <Text style={{ fontSize: "12px", color: "red" }}>
                      推荐尺寸1920*100,图片最大不能超过500KB
                    </Text>
                  </Text>
                </Form.Label>
                <Form.Control>
                  <Uploader>
                    <View
                      style={{ display: "flex", flexWrap: "wrap", gap: "5px" }}
                    >
                      {info.codeImage && (
                        <Uploader.Image
                          key={info.codeImage}
                          url={process.env.TARO_APP_API + info.codeImage}
                          mode="aspectFill"
                          onClick={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            priviewImage(info.codeImage, 0);
                          }}
                          onRemove={(e) => {
                            e.preventDefault();
                            e.stopPropagation();

                            setInfo({
                              ...info,
                              codeImage: "",
                            });
                          }}
                        ></Uploader.Image>
                      )}
                      {!info.codeImage && (
                        <Uploader.Upload
                          onClick={() => onUpload("codeImage", 1)}
                        />
                      )}
                    </View>
                  </Uploader>
                </Form.Control>
              </Form.Item>
              <Form.Item name="email">
                <Form.Label>公司电子邮箱</Form.Label>
                <Form.Control>
                  <Input
                    value={info.email}
                    onChange={(e) =>
                      setInfo({ ...info, email: e.detail.value })
                    }
                    placeholder="电子邮箱"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="email">
                <Form.Label>联系方式</Form.Label>
                <Form.Control>
                  <Input
                    value={info.phone}
                    onChange={(e) =>
                      setInfo({ ...info, phone: e.detail.value })
                    }
                    placeholder="联系方式"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="whatsapp">
                <Form.Label>whatsapp</Form.Label>
                <Form.Control>
                  <Input
                    value={info.whatsapp}
                    onChange={(e) =>
                      setInfo({ ...info, whatsapp: e.detail.value })
                    }
                    placeholder="whatsapp"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="address">
                <Form.Label>公司地址</Form.Label>
                <Form.Control>
                  <Textarea
                    value={info.address}
                    style={{ height: "5rem" }}
                    onChange={(e) =>
                      setInfo({ ...info, address: e.detail.value })
                    }
                    limit={255}
                    placeholder="公司地址"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="chinaAddress">
                <Form.Label>地图地址</Form.Label>
                <Form.Control>
                  <Textarea
                    value={info.chinaAddress}
                    onChange={(e) =>
                      setInfo({ ...info, chinaAddress: e.detail.value })
                    }
                    style={{ height: "5rem" }}
                    limit={255}
                    placeholder="地图地址"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="wxAccount">
                <Form.Label>微信账号</Form.Label>
                <Form.Control>
                  <Input
                    value={info.wxAccount}
                    onChange={(e) =>
                      setInfo({ ...info, wxAccount: e.detail.value })
                    }
                    placeholder="微信账号"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="producer">
                <Form.Label>产地</Form.Label>
                <Form.Control>
                  <Input
                    value={info.producer}
                    onChange={(e) =>
                      setInfo({ ...info, producer: e.detail.value })
                    }
                    placeholder="产地"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item name="establishment">
                <Form.Label>创立年份</Form.Label>
                <Form.Control>
                  <Input
                    value={info.establishment}
                    onChange={(e) =>
                      setInfo({ ...info, establishment: e.detail.value })
                    }
                    placeholder="创立年份"
                  />
                </Form.Control>
              </Form.Item>
              <Form.Item>
                <Form.Label>公司简介</Form.Label>
                <Form.Control>
                  <Textarea
                    value={info.introduction}
                    onChange={(e) =>
                      setInfo({ ...info, introduction: e.detail.value })
                    }
                    style={{ height: "5rem" }}
                    limit={255}
                  ></Textarea>
                </Form.Control>
              </Form.Item>
            </Cell.Group>
            <View style={{ margin: "16px" }}>
              <Button block color="primary" formType="submit">
                保存
              </Button>
            </View>
          </Form>
        </View>
      </View>
      <Footer />
    </View>
  );
}
